<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div ref="ele">
        <!-- 搜索 -->
        <label class="el-form-item-label">订单号</label>
        <el-input v-model="query.orderNumber" placeholder="订单号" clearable style="width: 155px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">煤种</label>
        <el-select v-model="query.categoryCode" filterable placeholder="全部" clearable style="width: 135px;" class="filter-item" @change="crud.toQuery">
          <el-option
            v-for="item in coalType"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">买家</label>
        <el-input v-model="query.buyUsername" placeholder="买家" clearable style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />

        <label class="el-form-item-label">煤矿名称</label>
        <el-select v-model="query.mineMouthId" filterable placeholder="全部" clearable style="width: 155px;" class="filter-item" @change="crud.toQuery">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.mineMouthName"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">煤炭名称</label>
        <el-input v-model="query.coalName" clearable placeholder="煤炭名称" style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">收货人</label>
        <el-input v-model="query.name" placeholder="发货人" clearable style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">收货人电话</label>
        <el-input v-model="query.phone" clearable placeholder="收货人电话" style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">下单日期</label>
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :height="tableHeight"
      border
      :data="crud.data"
      style="width: 100%;"
      :summary-method="getCommSummaries({customer: crud.totalObject, titleIndex: 0})"
      :show-summary="true"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column prop="orderNo" width="175" label="订单号" align="center" show-overflow-tooltip />
      <!--<el-table-column prop="merchantName" width="120" align="center" label="经销商" show-overflow-tooltip />-->
      <el-table-column prop="buyUsername" width="100" align="center" label="买家" show-overflow-tooltip />
      <el-table-column prop="coalName" width="90" align="center" label="煤炭名称" show-overflow-tooltip />
      <el-table-column prop="number" width="110" align="center" label="交易数量(吨)" show-overflow-tooltip />
      <el-table-column prop="sellPrice" width="110" align="center" label="销售价格(元/吨)" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="search-text1">{{ scope.row.sellPrice + scope.row.priceUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" width="100" align="center" label="总价格(元)" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="search-text1">{{ scope.row.totalPrice | nullFilter }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column prop="coalPrice" width="90" align="center" label="煤炭价格" show-overflow-tooltip>
        <template slot-scope="scope">
           <span class="search-text1">{{scope.row.coalPrice | nullFilter}}
             {{scope.row.priceUnit}}</span>
        </template>
      </el-table-column>
-->
      <el-table-column prop="freight" width="110" align="center" label="运费(元/每吨)" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="search-text1">{{ scope.row.freight | nullFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="totalFreight" width="100" align="center" label="总运费(元)" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="search-text1">{{ scope.row.totalFreight | nullFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="payTotalPrice" width="110" align="center" label="已支付煤款(元)" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="search-text1">{{ scope.row.payTotalPrice | nullFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="payTotalFreight" width="110" align="center" label="已支付运费(元)" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="search-text1">{{ scope.row.payTotalFreight | nullFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="orderStatus" align="center" width="90" show-overflow-tooltip label="订单状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.orderStatus === 1 ? 'success' : 'warning'">
            {{ scope.row.orderStatus | orderStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="orderWay" width="90" align="center" label="付款方式" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.orderWay === 1 ? "线上" : "线下" }}
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" show-overflow-tooltip width="80" label="收货人" />
      <el-table-column prop="phone" align="center" show-overflow-tooltip width="100" label="收货人电话" />
      <el-table-column prop="transportWay" width="90" align="center" label="运输方式" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.transportWay | transportFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="cleanWay" width="90" align="center" label="结算方式" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.cleanWay | cleanWayFilter }}
        </template>
      </el-table-column>

      <el-table-column prop="mineMouthName" width="120" align="center" label="所属煤矿" show-overflow-tooltip />
      <el-table-column prop="coalCategoryName" width="80" align="center" label="煤炭种类" show-overflow-tooltip />

      <el-table-column prop="address" width="110" align="center" label="收货详细地址" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.address | nullFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" align="center" show-overflow-tooltip width="120" label="购买时间">
        <template slot-scope="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="explain" width="90" align="center" label="购买说明" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.explain | nullFilter }}
        </template>
      </el-table-column>

      <el-table-column prop="updateTime" align="center" show-overflow-tooltip width="120" label="更新时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="操作" width="200"  align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-link"
                     v-permission="['admin','vehicleManages:relevance']"
                     type="primary"
                     @click="createBtnClick(scope.row)">分 配</el-button>
        </template>
      </el-table-column>-->
      <!--<el-table-column label="订单流程" align="center" width="95" fixed="right" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-popover trigger="click" placement="top" width="500">
            <el-table :data="scope.row.merchantOrderRecords">
              <el-table-column width="100" property="username" label="操作人账号"></el-table-column>
              <el-table-column width="90" property="orderStatus" label="操作状态">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.orderStatus === 1 ? 'success' : 'warning'">
                    {{ scope.row.orderStatus | orderStatusFilter }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column width="120" property="operationTime" show-overflow-tooltip label="操作时间">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.operationTime)}}</span>
                </template>
              </el-table-column>
              <el-table-column property="remark" show-overflow-tooltip label="操作备注"></el-table-column>
            </el-table>
            <a slot="reference" class="name-wrapper">
              <el-tag size="medium">操作流程</el-tag>
            </a>
          </el-popover>
        </template>
      </el-table-column>-->
    </el-table>
    <!--分页组件-->
    <pagination />
    <div class="panel">
      <form-panel v-if="showFormPanel" :show-form-panel.sync="showFormPanel" :item="selectedItem" @refreshList="crud.toQuery" />
    </div>
    <el-dialog
      title="拒绝原因"
      class="tiny-mce-dialog"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-form ref="causeValue" :model="causeValue" :rules="causeValues" size="small" label-width="80px">
        <el-card class="box-card">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="原因" prop="comments" label-width="80px">
                <el-input
                  v-model="causeValue.comments"
                  clearable
                  type="textarea"
                  placeholder="请输入拒绝原因"
                  :autosize="{ minRows: 6, maxRows: 10}"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-loading="fullscreenLoading" type="success" @click="save(false)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import crudUnconfirmedOrder from '@/api/order/unconfirmedOrder'
import CRUD, { crud, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import Form from './form'

export default {
  name: 'FinishedOrder',
  components: { pagination, crudOperation, rrOperation, DateRangePicker, 'form-panel': Form },
  mixins: [presenter(), header(), crud()],
  cruds() {
    return CRUD({ title: '待确认订单列表', url: 'api/orderMerchant/finishedOrderList', query: { orderStatus: 3, categoryCode: null }, idField: 'orderId', sort: 'orderId,desc', crudMethod: { ...crudUnconfirmedOrder }})
  },
  data() {
    return {
      showFormPanel: false,
      dialogVisible: false,
      fullscreenLoading: false,
      causeValue: {},
      orderId: null,
      height: this.getTableHeight({}),
      tableHeight: this.height,
      echodisplaylist: [],
      selectedItem: {},
      dialogFormVisible: false,
      options: [],
      merchant: [],
      coalType: [
        { name: '全部', ecode: null, id: null }
      ],
      coalName: [],
      coalData: null,
      coalValueData: {},
      status: [
        { key: '全部', value: null },
        { key: '已下单', value: 1 },
        { key: '用户取消', value: 2 },
        { key: '商户确认', value: 3 },
        { key: '商户拒绝', value: 4 },
        { key: '关闭（24小时）', value: 5 },
        { key: '已支付', value: 6 },
        { key: '商户确认', value: 7 }
      ],
      priceUnit: '',
      baseCatesValue: [],
      forms: {
        coalInfos: []
      },
      causeValues: {
        comments: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' }
        ]
      },
      permission: {
        add: ['admin', 'coalProducts:add'],
        edit: ['admin', 'coalProducts:edit'],
        del: ['admin', 'coalProducts:del']
      }
    }
  },

  created() {
    this.crud.optShow = {
      reset: true,
      add: false,
      edit: false,
      del: false,
      download: false
    }
  },
  mounted: function() {
    this.tableHeight = this.height - this.$refs.ele.clientHeight
    this.getCategory()
    this.search()
  },
  methods: {
    save(val) {
      const self = this
      const pram = {
        id: self.orderId,
        msg: self.causeValue.comments,
        falg: val
      }
      self.$refs['causeValue'].validate((valid) => {
        if (valid) {
          self.fullscreenLoading = true
          self.$http.put('/api/orderMerchant/refuse', pram)
            .then(function(res) {
              self.fullscreenLoading = false
              self.dialogVisible = false
              self.crud.toQuery()
            }).catch(function(error) {
              self.fullscreenLoading = false
              console.log(error)
            })
        }
      })
    },
    createBtnClick(value) {
      this.selectedItem = value.orderId
      this.showFormPanel = true
    },
    refuseBtnClick(value) {
      this.orderId = value.orderId
      this.dialogVisible = true
    },
    getCurrentMonthFirst() {
      var date = new Date()
      date.setDate(1)
      date.setHours(0)
      date.setSeconds(0)
      date.setMinutes(0)
      return date
    },
    getCommSummaries({ column, customer, title = '合计', titleIndex }) {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
      return function(param) {
        const sums = []
        const { columns, data } = param
        columns.forEach((columnItem, index) => {
          if ((titleIndex === undefined && columnItem.type === 'index') || index === titleIndex) {
            sums[index] = title
          } else if (customer) {
            sums[index] = customer[columnItem.property] === null || customer[columnItem.property] === undefined || customer[columnItem.property] === '' ? '-' : customer[columnItem.property]
          } else {
            const sumList = []
            column.forEach((e) => {
              if (e.toString().includes('-')) {
                for (let i = Number(e.split('-')[0]); i <= Number(e.split('-')[1]); i++) {
                  sumList.push(i)
                }
              } else {
                sumList.push(Number(e))
              }
            })
            if (sumList.includes(index)) {
              const values = data.map(e => Number(e[columnItem.property]))
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] += ''
              } else {
                sums[index] = '-'
              }
            }
          }
        })
        return sums
      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields()
    },
    objectKey(key, value) {
      const keyValue = {}
      keyValue[key] = value
      return key
    },
    search() {
      const self = this
      self.$http.get('/api/mineMouth/getMineMouth').then(function(value) {
        self.options = value
      })
      self.$http.get('/api/systemController/getMerchant').then(function(value) {
        if (value.ok) {
          self.merchant = value.data
        }
      })
    },
    getCategory() {
      const self = this
      self.$http.get('/api/coalCategory/query').then(function(value) {
        self.coalType = self.coalType.concat(value)
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>

<style scoped>

</style>
